package com.atguigu.fruit.servlets;

import com.atguigu.fruit.dao.FruitDAO;
import com.atguigu.fruit.dao.impl.FruitDAOImpl;
import com.atguigu.fruit.pojo.Fruit;
import com.atguigu.myssm.myspringmvc.ViewBaseServlet;
import com.atguigu.myssm.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

//Servlet从3.0版本开始支持注解方式的注册
@WebServlet("/index")
public class IndexServlet extends ViewBaseServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1、设置字符集编码
        req.setCharacterEncoding("UTF-8");
        HttpSession session = req.getSession();
//        为了没有传页码，我默认让你加载第一页
        Integer pageNo = 1;
        String keyword = "";
//        获取oper这个表识，主要是为了区分是点击了查询，还是默认首次或点击上一页或下一页？
//        如果oper是空的，说明 通过表单的查询按钮点击过来的
//        如果不是空的话说明就是默认首次或点击上一页或下一页
        String oper = req.getParameter("oper");
        keyword = req.getParameter("keyword");
        if (StringUtil.isNotEmpty(oper)&&"search".equals(oper)){
//            说明 通过表单的查询按钮点击过来的
            pageNo = 1;
            if (StringUtil.isEmpty(keyword)){
                keyword = "";
            }
            session.setAttribute("keyword",keyword);
        }else {
//            说明此处不是点击查询发送过来的请求，
//            而是点击了上一页/下一页/直接在地址栏输入网址的默认加载
            String pageNoStr = req.getParameter("pageNo");
            if (StringUtil.isNotEmpty(pageNoStr)){
                pageNo = Integer.parseInt(pageNoStr);
            }
            Object keywordObj = session.getAttribute("keyword");
            if (keywordObj != null){
                keyword = (String) keywordObj;
            }else {
                keyword = "";
            }


        }
        session.setAttribute("pageNo",pageNo);
        FruitDAO fruitDAO = new FruitDAOImpl();
        List<Fruit> fruitList = fruitDAO.getFruitList(keyword, pageNo);

        session.setAttribute("fruitList",fruitList);
//        获取总记录数
        int fruitCount = fruitDAO.getFruitCount(keyword);
//        计算总页数
        int pageCount = (fruitCount+5-1)/5;
        session.setAttribute("pageCount",pageCount);
//        转发到index界面上
        super.processTemplate("index",req,resp);


    }
}
